<template>
	<view class="content" style="padding-bottom:160rpx;">
	    <!-- 公共组件-每个页面必须引入 -->
	    <public-module></public-module>
		  <div class="con-list-div">
				<div class="sale-list-item arrangeGoods-item" v-for="(item,index) in list" :key="index">
				 <div class="sale-top"  style="cursor: pointer">
					<div class="sale-compeny" style="cursor: pointer">{{item.fileName}}</div>
				  </div>
				  <div class="sale-con" style="cursor: pointer">
					 <div class="goods-middle">
						 <div class="goods-subtxt">商品名称：{{item.categoryName}}/{{item.brandName}}/{{item.goodsSn}}</div>
						 <div class="goods-subtxt">
							类型：{{item.typeCode | fifCode}}
							<span v-if="item.className != ''" style="padding-left:20px">分类：{{item.className}}</span>
						 </div>
						 <div class="goods-subtxt" >
							上传时间：{{item.createTime}}
						 </div>
						 <div class="goods-subtxt"  >
							 上传类型：{{item.userTypeName}}
						 </div>
					 </div>
				  </div>
				  <div class="sale-btn"  >
					    <u-button text="删除" size="small" shape="circle" :custom-style="style2" type="error" @click="delItem(item)"></u-button>
					    <u-button text="编辑" size="small" shape="circle" :custom-style="style2" type="primary" @click="showSetting(item)"></u-button>
						<u-button text="下载附件" size="small" shape="circle" :custom-style="style2" type="success" @click="downImg(item)"></u-button>
				  </div>
				</div>
		  </div>
		   
		  <div style="padding-bottom:40rpx;" >
			  <u-loadmore :status="status"></u-loadmore>
		  </div>
		  
		  <view class="page-bottom-btn" style="padding:0 24rpx">
		     <u-button text="新增产品文档" type="primary" shape="circle" @click="showSetting('')"></u-button>
		  </view>
		  
		  <!--编辑文档-->
		  <u-popup :show="show" mode="bottom" :round="10" @close="closeShow">
		   <div class="popupTitle">文档信息</div>
		  	<div class="popup-con" style="height:calc(100vh - 200px);overflow-y: auto;">
		  		<u-form labelPosition="left" :model="value" :rules="rules" ref="form" labelWidth="140" errorType="toast">
					<u-form-item required label="分类/厂家/牌号" prop="goodsName" borderBottom @click="showGoods()">
						<u--input :value="value.goodsName" disabled disabledColor="#ffffff" placeholder="请选择商品" border="none" inputAlign="right" style="pointer-events: none"></u--input>
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</u-form-item>
				
					<u-form-item label="资料名称" required  borderBottom prop="fileName">
						<u--input v-model="value.fileName" border="none" inputAlign="right" placeholder="请输入资料名称"></u--input>
					</u-form-item>
					<u-form-item required label="类型" prop="typeCode" borderBottom @click="showChoose('typeCode')">
						<u--input :value="value.typeCode | fifCode" disabled disabledColor="#ffffff" placeholder="请选择类型" border="none" inputAlign="right" style="pointer-events: none"></u--input>
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</u-form-item>
					
					<u-form-item required label="分类" prop="classId" v-if="value.typeCode == 'factory' || value.typeCode == 'third'" borderBottom @click="showChoose('classId')">
						<u--input :value="value.classId | fifClass(classList)" disabled disabledColor="#ffffff" placeholder="请选择分类" border="none" inputAlign="right" style="pointer-events: none"></u--input>
						<u-icon slot="right" name="arrow-right" ></u-icon>
					</u-form-item>
		
					<u-form-item label="附件" labelPosition='top' prop="fileUrl">
					    <div style="margin-bottom:10px;">
							<span v-if="value.fileUrl != ''">{{value.fileUrl}}</span>
					    </div>
						<u-upload url="https://upload.qiniup.com" @afterRead="handleAfterRead"  :accept="accept" @delete="deleteImg()"
						 :maxCount="1" style="width:200rpx;height:200rpx;margin-top:10px;">
						<div style="display: flex;flex-direction: column;align-items: center;justify-content: center;width: 80px;height: 80px;background-color: #f4f5f7;border-radius: 2px;margin: 0 8px 8px 0;sbox-sizing: border-box;margin-top:10rpx">
							<u-icon name="file-text-fill" size="28" color="#D3D4D6"></u-icon>
						</div>
						</u-upload>
					</u-form-item>
		  		</u-form>
		  	</div>
		  	<div class="u-flex popup-bottom">
		  		<u-button text="取消"  shape="circle" @click="closeShow"></u-button>
		  		<u-button text="确认"  shape="circle" type="primary" @click="saveForm" :loading="btnLoading"></u-button>
		  	</div>
		  </u-popup>  
		  
		  <u-picker :show="show2" :columns="columns" @confirm="confirm" :keyName="keyName" @cancel="closeShow2"></u-picker>
		  
		  <!--选择商品-->
		  <u-popup :show="show3" mode="bottom"  @close="closeShow3" :round="23">
		  	<div>
		  		<div class="popupTitle" style="text-align: left;padding-left:16px;">
		  			<span style="padding-left:20rpx;vertical-align: middle;">选择商品</span>
		  		</div>
		  		<div class="popup-con" style="padding:0 24px 16px 24px;margin-top:10px;height: 80vh;overflow: auto;padding-bottom: 100rpx;">
					<div style="font-size: 14px;color:#000;border-bottom: 1px solid #eee;padding:10rpx 0" v-for="(item,index) in goodsList" :key='index' @click="chooseGoods(item)">	
						{{item.parentCategoryName}}/{{item.categoryName}} / {{item.brandName}} / {{item.goodsSn}}
					</div> 
		  		</div>
		  	</div>
		  </u-popup> 
	</view>
</template>

<script>
const defaultValue = {
  "fileId"     : 0,  //文件ID，为0表示新增
  "fileName"   : "", //资料名称
  "fileUrl"    : "", //附件地址
  "categoryId" : '',  //商品分类ID
  "brandId"    : '',  //品牌ID
  "goodsSn"    : "",  //牌号
  "classId"    : '',        //资料类型ID
  "typeCode"   : "", //类型(原厂:factory，第三方:third，物流表:properties，其它:other)
  sapGoodsNo:''
};
	import{imgCheck} from '@/plugins/upload/upload.js'
	import {setDocumentFile,delDocumentFile,getDocumentClassList,getBrandList,getDocumentFileList} from '@/config/goods.js'
	import { myGoodsList } from '@/config/api2.js'
	import {pageSeo} from '@/config/api.js'
	import {downloadFun,saveImg} from '@/plugins/utils.js'
	import store from '@/store';
	export default {
	    components:{
	       
	    },
	    data() {
	        return {
		
				status: 'loadmore',
				list: [],
				pageNum: 0,
				pageSize:10,
				count:0,
				current:0,
				style2:{
					width:'160rpx',
					border:'none',
					marginLeft:'10rpx'
				},
		        rules:{
				   fileName: [{
						required: true,
						message: '请输入文档名称',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
					fileUrl: [{
						required: true,
						message: '请上传附件',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
					goodsName: [{
						required: true,
						message: '请选择商品',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
					classId: [{
						required: true,
						message: '请选择分类',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
					typeCode: [{
						required: true,
						message: '请选择类型',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
		        				
				},
				value:JSON.parse(JSON.stringify(defaultValue)),
				btnLoading:false,
				show:false,
			    fileList1: [],
				codeList:[
				        {code:'factory',name:'原厂资料'},
				        {code:'third',name:'第三方'},
				        // {code:'properties',name:'物性表'},
				        {code:'other',name:'其它资料'},
				      ],
					  
			    classList:[],
			
				
				show2:false,
				fileList:[],
				file:'',
				
				columns:[],
				showType:'',
				keyName:'',
				goodsName:'',
				// #ifdef H5
				accept:'file',
				// #endif	
				// #ifdef MP
				accept:'all',
				// #endif	
				show3:false,
				goodsList:[]
				
				
	        }
	    },
	    async onLoad(e) {
				await this.$onLaunched;
				this.clearData();
				this.getList();
				this.getClassList();
				this.getMyGoodsList()
	    },
		async onShow() {
			// #ifdef H5
			pageSeo({pageType: 'indexPage'}).then((res)=>{
				document.title = res.pageTitle;
			})
			// #endif	
		},
		onReachBottom() {
			if(this.list.length >= this.count) {
				this.status = 'nomore';
				return ;
			}
			this.pageNum = ++ this.pageNum;
			this.getList()
			
		},
		filters: {
		    fifitem(item){
		      return item.categoryName+'/'+item.brandName+'/'+item.goodsSn
		    },
		    fifCode(val){
		      if(val == 'factory'){
		        return '原厂资料'
		      }else if(val == 'third'){
		        return '第三方'
		      }else if(val == 'properties'){
		        return '物性表'
		      }else if(val == 'other'){
		        return '其它资料'
		      }
		    },
			fifClass(val,list){
				let i = list.findIndex((el)=>{
					return el.classId == val
				})
				if(i != -1){
					return list[i]['className']
				}else{
					return ''
				}
				
			},
		  },
		  
	    methods: {
			chooseGoods(item){
				this.value.categoryId = item.categoryId;
				this.value.categoryName = item.categoryName;
				this.value.brandId = item.brandId;
				this.value.brandName =item.brandName;
				this.value.goodsSn = item.goodsSn;
				this.value.sapGoodsNo = item.sapGoodsNo;
				this.value.goodsName = item.categoryName+'/'+item.brandName+'/'+item.goodsSn
				this.closeShow3()
			},
			closeShow3(){
				this.show = true;
				this.show3 = false
			},
			getMyGoodsList() {
			  let data = {};
			  data.keyword = '';
			  data.pageNum = this.pageNum;
			  data.pageSize = 10000;
			  myGoodsList(data).then(res => {
				this.goodsList = res.list;
			  })
			},
			showGoods(){
				this.show3 = true
			},
			confirm(e){
			   switch (this.showType){
			   	case 'typeCode':
				   this.value['typeCode'] = e.value[0]['code']
			   	   break;
			    case 'classId':
			   	  this.value['classId'] = e.value[0]['classId']+''
			   	  break;
			   }
			   this.closeShow2()
			},
			closeShow2(){
				this.show2 = false
				this.show = true;
			},
			showChoose(key){
				console.log(key)
				this.showType = key
				this.show = false
				switch (key){
					case 'typeCode':
					   this.columns = [this.codeList]
					   this.keyName = 'name'
					   this.show2 = true
					   break;
				   case 'classId':
					  this.columns = [this.classList]
					  this.keyName = 'className'
					  this.show2 = true
					  break;
				}
			},
		 getClassList(){
			  getDocumentClassList({pageNum: 1,pageSize: 10000}).then((res)=>{
				this.classList = res.list
			  })
			},
			delItem(item) {
			  uni.showModal({
			    title: '删除提示',
			    content: '您将删除该文档',
			    success: (res) => {
			      if (res.confirm) {
			        delDocumentFile({
			          fileId: item.fileId
			        }).then(() => {
			          this.searchList()
			        })
			
			      } else if (res.cancel) {
			        console.log('用户点击取消');
			      }
			    }
			  });
			
			},
			
			downImg(item){
				if(item.fileUrl != ''){
					const fileType = item.fileUrl.substring(item.fileUrl.lastIndexOf('.'));
					if (fileType == '.pdf') {
						downloadFun(item.fileUrl)
					} else {
						// #ifdef MP
						saveImg(item.fileUrl)
						// #endif
						// #ifdef H5
						uni.previewImage({ urls: [item.fileUrl] });
						// #endif
					}
				}else{
					uni.showToast({
						title:'此文档没有附件',
						icon:'none'
					})
				}
				
				
			},
			
			//删除图片
			deleteImg(event){
				this.value['fileUrl'].splice(0,1)
			},
			handleAfterRead(event) {
				console.log("event",event)
				if(event.file.size>2*1024*1000){
					uni.showToast({
						title:'图片大小超过2M，请重新选择照片',
						icon:'none'
					})		
					return
				}
				let fileUrl = event.file.url
				let fileType = event.file.url.substring(event.file.url.lastIndexOf('.'));
				
			     // #ifdef H5
				   fileUrl = event.file.name
				   fileType =event.file.name.substring(event.file.name.lastIndexOf('.')); 
				   
				 // #endif
				 
				if(fileType !== '.jpg' && fileType !== '.jpeg' && fileType !== '.png' && fileType !== '.pdf'){
					uni.showToast({
					  title: '请上传jpg、jpge或png的图片或pdf文件！',
					  icon: 'none',
					  duration: 2000,
					});
				  return false;
				}
				uni.showLoading({
					title: '上传中',
				});
				imgCheck(event.file.url,fileType).then((res)=>{
					if(res != ''){
						this.value['fileUrl'] = res
							// console.log(this.value['fileUrl'] )
					}
					uni.hideLoading()
				}).catch(()=>{
					uni.hideLoading()
				})
			},
			
			showSetting(item){
				this.show = true
				if(item){
					this.value = JSON.parse(JSON.stringify(item))
					this.value.classId = item.classId == 0 ? '' : item.classId+''
					this.value.goodsName = item.categoryName+'/'+item.brandName+'/'+item.goodsSn
					// this.value.fileUrl = []
					// this.value.fileUrl.push({url:item.fileUrl})    
					this.value.fileUrl = item.fileUrl
				  }else{
					this.value = JSON.parse(JSON.stringify(defaultValue))
					this.value.goodsName = ''
				  }
				  console.log(this.value)
			},
			
		   saveForm(){
			   console.log(this.value)
			   this.$refs.form.validate().then(res => {
				   this.btnLoading = true;
				   let  data = JSON.parse(JSON.stringify(this.value));
				   // data.fileUrl = this.value['fileUrl'][0]['url']
					 setDocumentFile(data).then(()=>{
						   this.btnLoading = false;
						   this.closeShow();
						   uni.showToast({
							 title: '文档信息保存成功！',
							 icon: 'none',
							 duration: 2000,
						   });
						   this.searchList()
					 }).catch(()=>{
						   this.btnLoading = false;
					 })
			   }).catch(errors => {
				
			   })
		   },
		   
		   closeShow(){
			   this.show = false
		   },
		
			searchList(){
				this.clearData();
				this.getList()
			},
			
			
			
			//清除数据
			clearData(){
					this.pageNum = 1;
					this.list = [];
					this.status = 'loadmore';
					this.count = 0;
			},
			
			getList(){
				let data = {};
				data.pageSize = 10;
				data.pageNum = this.pageNum;
	
				this.status = 'loading';
			    return	getDocumentFileList(data).then((res)=>{
					  this.list = this.list.concat(res.list ? res.list : [] );
					  this.count = res.count;
					  if(this.list.length >= this.count) {
					  	this.status = 'nomore';
					  }else{
					  	this.status = 'loadmore';
					  }
	
				}).catch(()=>{
					this.status = 'loadmore';
				})
			},
		
	    },
	
	}
</script>

<style lang="scss">
@import '@/style/common.scss';
.con-list-div{
    padding:8px 12px;
	.sale-list-item{
		  cursor: pointer;
		  background: #fff;
		  margin-bottom:$marginSpace;
		  border-radius: 8px;
		  font-size:$m-font;
		  line-height: 24px;
		  padding:0 16px;
		  .sale-top{
			  padding-top:5px;
			  line-height:40px;
			  border-bottom:0.8px solid $border-color;
			  @include flexbox(space-between,center);
			  .sale-compeny{
				  @include textoverflow(1);
				  padding-right:16px;
			  }
			  .sale-state{
				  color:$u-primary;
			  }
		  }
		  .sale-con{
			 padding-top:5px; 
			.goods-top{
				@include flexbox(space-between,center);
				.goods-name{
					font-size:$m-font;
					padding-right:20px;
				}
				.goods-price{
					font-size:$m-font;
					font-weight:bold;
					white-space:nowrap;
					.label{
						font-size:10px
					}
				}
			}
			.goods-middle{
				.goods-subtxt{
					font-size:$s-font;
					color:$g-font-color;
				}
			}
		  }
		  .sale-bottom{
			line-height:40px;
			text-align: right;
			color:#888;
		  }
		  .sale-btn{
			padding:10px 0;
			text-align: right;
			border-top:0.8px solid $border-color;
			overflow: hidden;
			@include flexbox(flex-end,center);
		  }

		}
}


.popupTitle{
	font-size:$b-font;
	font-weight: bold;
	text-align: center;
	line-height: 50px;
}
.popup-con{
	padding:0 16px 16px 16px;
}
.popup-con#inovlceList{
	
	.u-radio-label--right{
		padding:8px 0 !important
	}
}
.popup-bottom{
	background: #fff;
	margin-top:10px;
	padding:16px;
}
.popup-bottom-fixed{
	position: fixed;
	width:100%;
	padding:16px;
	box-sizing: border-box;
	bottom:0
}
#invoiceUpdiv .u-upload{
	align-items: center;
}
#invoiceRadio .u-radio{
	margin-right:30px
}
    


</style>

